<!--用车申请页-->
<template>
  <div style="height: 6vh;background-color:#fff;padding:10px 20px;">
    <span style="line-height:60px;font-size:20px;">申请单列表</span>
    <el-button type="primary" style="float:right;margin-top:13px;" @click="addApplicationDialogVisible = true"
               :disabled="user.parentId==null">
      <!--               v-if="user.parentId!=null">-->
      申请用车
    </el-button>
  </div>
  <!-- 申请用车弹窗 -->
  <el-dialog title="创建申请单" v-model="addApplicationDialogVisible" style="width:1000px;padding:40px;"
             :before-close="handleClose">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="用车人">
            <el-input readonly :value="user.username"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="使用时间">
            <el-date-picker
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                v-model="dateRange"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="车辆出发地">
            <el-input placeholder="请输入" v-model="addApplicationForm.departureAddr"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车辆目的地">
            <el-input placeholder="请输入" v-model="addApplicationForm.destinationAddr"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="用车事由">
            <el-input placeholder="请输入" type="textarea" resize="none" :rows="3"
                      v-model="addApplicationForm.reason"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input placeholder="请输入" type="textarea" resize="none" :rows="3"
                      v-model="addApplicationForm.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="驾照">
            <el-upload
                v-if="!hasUploaded"
                v-model:file-list="fileList"
                v-model:action="actionUrl"
                name="file"
                limit="1"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="handSuccess"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
            <div v-else style="position: relative;">
              <el-image
                  v-for="file in fileList"
                  :src="BASE_URL+'/'+file.response.data"
                  fit="cover"
                  style="width: 150px; height: 150px;border-radius: 5px;"
                  @mouseover="showMask = true"
              ></el-image>
              <div v-show="showMask"
                   style="width: 150px; height: 150px;border-radius: 5px;
                   background-color: #666666;opacity: 0.5;color: #fff;position: absolute;top: 0;left: 0;
                   text-align: center;line-height: 150px;cursor: zoom-in;"
                   @mouseout="showMask = false"
                   @click="handlePictureCardPreview"
              >
                点击预览
              </div>
              <el-button type="danger" @click="handleRemove" link>删除</el-button>
            </div>
            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl"/>
            </el-dialog>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审批人">
            <el-row :gutter="10">
              <el-col :span="12">
                <el-tag type="primary">
                  <el-icon style="margin-right:5px;position:relative;top:2px;">
                    <User/>
                  </el-icon>
                  <span>{{ auditUserList[0].username }}</span>
                </el-tag>
              </el-col>
              <el-col :span="12" v-if="auditUserList[1]">
                <el-tag type="primary">
                  <el-icon style="margin-right:5px;position:relative;top:2px;">
                    <User/>
                  </el-icon>
                  <span>{{ auditUserList[1].username }}</span>
                </el-tag>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="addApplication">确定</el-button>
    </template>
  </el-dialog>

  <!-- 用车申请列表 搜索卡片 -->
  <el-card style="margin: 20px;">
    <el-form style="padding-top:10px;">
      <el-row :gutter="30">
        <el-col :span="5">
          <el-form-item label="出发地">
            <el-input placeholder="请输入出发地" v-model="query.departureAddr"
                      @keydown.enter="loadApplicationList"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="目的地">
            <el-input placeholder="请输入目的地" v-model="query.destinationAddr"
                      @keydown.enter="loadApplicationList"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="申请单状态">
            <el-select placeholder="请选择" v-model="query.status" @change="loadApplicationList">
              <el-option label="已发起" value="10"></el-option>
              <el-option label="撤销" value="20"></el-option>
              <el-option label="审核中" value="30"></el-option>
              <el-option label="驳回" value="40"></el-option>
              <el-option label="已通过" value="50"></el-option>
              <el-option label="分配用车" value="60"></el-option>
              <el-option label="工单结束" value="70"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="loadApplicationList">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <!-- 用车申请表格 -->
  <el-card style="margin:20px">
    <el-table :data="tableData">
      <el-table-column type="index" width="80" align="center" prop="id" label="编号"></el-table-column>
      <el-table-column align="center" prop="username" label="申请人"></el-table-column>
      <el-table-column align="center" prop="departureAddr" label="出发地"></el-table-column>
      <el-table-column align="center" prop="destinationAddr" label="目的地"></el-table-column>
      <el-table-column align="center" prop="reason" label="用车原因"></el-table-column>
      <el-table-column align="center" prop="auditUserNameList" label="审批人"></el-table-column>
      <el-table-column align="center" prop="startTime" label="使用开始时间"></el-table-column>
      <el-table-column align="center" prop="endTime" label="使用结束时间"></el-table-column>
      <el-table-column align="center" prop="status" label="申请单状态" :formatter="statusTypeFormat"></el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" link :disabled="scope.row.status!=10" @click="cancelApp(scope.row.id)">撤销</el-button>
        </template>
      </el-table-column>
    </el-table>

  </el-card>
</template>
<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import qs from "qs";

/**图片上传相关代码开始**/
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
// 定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref(BASE_URL + '/v1/file/upload');
// 定义变量用来判断是否上传过图片
const hasUploaded = ref(false);
// 定义变量用于全局储存上传的图片路径
const imgUrlGlobal = ref('');
// 定义变量决定遮罩是否显示
const showMask = ref(false);
// 图片上传变动
const handSuccess = () => {
  hasUploaded.value = true;
  imgUrlGlobal.value = fileList.value[0].response.data;
}

// 移除图片
const handleRemove = () => {
  axios.delete(BASE_URL + '/v1/file/delete?imgUrl=' + imgUrlGlobal.value)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('删除成功!');
          hasUploaded.value = false;
          fileList.value = [];
        } else {
          ElMessage.error(response.data.msg);
        }
      })
}

// 图片上传后预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = BASE_URL + '/' + imgUrlGlobal.value
  dialogVisible.value = true;
  console.log(dialogImageUrl.value)
}

/** 获取用户信息及其审批人信息 */
// 定义变量获取用户信息
const user = ref(getUser());
// 定义数组保存多个审批人 => 申请弹窗显示审批人姓名
const auditUserList = ref([]);
// 定义数组保存多个审批人的id => 生成多个审批单
const auditUserIdList = ref([]);
// 加载审批人方法
const loadAuditUser = () => {
  let parentId = user.value.parentId;
  // 根据当前登录人的父级id，从后端获取此人的直属领导及直属领导的直属领导（如果存在）
  axios.get(BASE_URL + '/v1/user/select/audit/' + parentId)
      .then((res) => {
        if (res.data.code == 2000) {
          auditUserList.value = res.data.data;
          // 遍历上方VO，取出id存入审批人id数组
          auditUserList.value.forEach((item) => {
            auditUserIdList.value.push(item.id);
          })
          console.log(auditUserList.value);
          console.log(auditUserIdList.value);
        } else {
          ElMessage.error(res.data.msg);
        }
      })
}

/** 新增申请单和审批单 */
const addApplicationDialogVisible = ref(false);
const addApplicationForm = ref({
  departureAddr: '',
  destinationAddr: '',
  reason: '',
  remark: ''
});
const dateRange = ref([]);
// 发送新增请求
const addApplication = () => {
  // 判断起止时间是否为空
  if (dateRange.value.length == 0) {
    ElMessage.error('请选择起止时间！');
    return;
  }
  // 判断申请单数据是否为空
  if (addApplicationForm.value.departureAddr == '' || addApplicationForm.value.destinationAddr == '' || addApplicationForm.value.reason == '') {
    ElMessage.error('申请单数据不能为空！');
    return;
  }
  if (fileList.length == 0) {
    ElMessage.error('请上传驾照图片！');
  }
  addApplicationForm.value.userId = user.value.id;
  addApplicationForm.value.username = user.value.username;
  addApplicationForm.value.startTime = dateRange.value[0];
  addApplicationForm.value.endTime = dateRange.value[1];
  addApplicationForm.value.imgUrl = "/" + imgUrlGlobal.value;
  addApplicationForm.value.auditUserIdList = auditUserIdList.value;
  console.log(addApplicationForm.value);
  let data = qs.stringify(addApplicationForm.value);
  axios.post(BASE_URL + '/v1/application/save', data)
      .then((res) => {
        if (res.data.code == 2000) {
          ElMessage.success('新增成功！');
          addApplicationDialogVisible.value = false;
          addApplicationForm.value = {};
          fileList.value = [];
          hasUploaded.value = false;
          dateRange.value = [];
          loadApplicationList();
        } else {
          ElMessage.error(res.data.msg);
        }
      })
}

// 关闭弹窗
const handleClose = () => {
  addApplicationDialogVisible.value = false;
  addApplicationForm.value = {};
  handleRemove();
  fileList.value = [];
};

/** 展示申请单列表 */
// 准备对象用于保存申请单列表
const tableData = ref([]);
// 定义变量保存申请单列表查询条件
const query = ref({
  departureAddr: '',
  destinationAddr: '',
  status: '',
});
// 定义变量用于保存电池类型数据（来自字典）
const statusTypeArr = ref([]);
// 加载申请单列表方法
const loadApplicationList = () => {
  let data = qs.stringify(query.value);
  axios.get(BASE_URL + '/v1/application/select?' + data)
      .then((res) => {
        if (res.data.code == 2000) {
          tableData.value = res.data.data;
          console.log(tableData.value);
        } else {
          ElMessage.error(res.data.msg);
        }
      })
}
// 重置查询条件方法
const resetSearch = () => {
  query.value = {}
  loadApplicationList();
}
// 定义转换申请单状态显示为文字的方法
const statusTypeFormat = (row, column, cellValue, index) => {
  if (!statusTypeArr.value) {
    return cellValue;
  }
  for (let i of statusTypeArr.value) {
    if (i.value == row.status) {
      cellValue = i.label;
    }
  }
  return cellValue;
}

/** 撤销申请单 */
const cancelApp=(id)=>{
  axios.post(BASE_URL+'/v1/application/cancel/'+id)
      .then((res)=>{
        if(res.data.code==2000){
          ElMessage.success('撤销成功！');
          loadApplicationList();
        }else{
          ElMessage.error(res.data.msg);
        }
      })
}

onMounted(() => {
  loadAuditUser();
  loadApplicationList();
  loadDictOptions(statusTypeArr, 'application_status');

})
</script>

<style scoped>

</style>